
function SingleUpload(options) {
  const { el, url } = options;

  this.inputDom = null;
  this.url = url;
  this.events = new EventBus();

  if (typeof el === 'string' && el.indexOf('#') > -1) {
    this.inputDom = document.getElementById(el.replace('#', ''));
  } else {
    this.inputDom = document.getElementsByClassName(el)[0]
  }

  this.inputDom.addEventListener('change', ev => {
    console.warn('SingleUpload', ev);
    const file = ev.target.files[0];
    const formData = new FormData();
    formData.append("file", file);
    this.postSource(formData);
  })
}

SingleUpload.prototype = {

  postSource(formData) {
    axios({
      method: "post",
      url: this.url,
      data: formData,
      onUploadProgress: this.uploadProgress.bind(this)
    }).then(res => {
      const { data } = res;
      this.events.publish('upload:success', { data, el: this.inputDom });
    }).catch(err => {
      this.events.publish('upload:error', err);
    })
  },

  uploadProgress(evt) {
    if (evt.lengthComputable) {
      const percent = Math.round(evt.loaded * 100 / evt.total);
      this.events.publish('upload:progress:success', { percent: `${percent}%` });
    }
    else {
      this.events.publish('upload:progress:error');
    }
  }
}


function EventBus() {
  this.events = {};
}

EventBus.prototype = {
  // 订阅事件
  subscribe: function(eventName, fn) {
    if (!this.events[eventName]) {
      this.events[eventName] = new Set();
    }
    if (typeof fn !== 'function') {
      return;
    }
    this.events[eventName].add(fn);
  },

  // 取消订阅
  unsubscribe: function(eventName, fn) {
    const eventList = this.events[eventName];
    if (eventList.size > 0 && eventList.has(fn)) {
      this.events[eventName].delete(fn);
    }
  },

  // 发布事件通知
  publish: function(eventName, data) {
    if (this.events[eventName] && this.events[eventName].size) {
      const eventList = this.events[eventName];
      for (let event of eventList) {
        event && event(data);
      }
    }
  }
}